#include "metaclass.h"
#include <QDebug>

QMap<QString, QObject*>* MetaClass::instanceMap = new QMap<QString, QObject*>();

MetaClass::MetaClass(QObject *parent) :
    QObject(parent)
{
}

MetaClass::MetaClass(const QString& className, const QString& libName, const QString& libPath)
{
    this->className = className;
    this->libName = libName;
    setLibPath(libPath);
}

MetaClass::~MetaClass()
{

}

QString const & MetaClass::getLibName() const
{
    return this->libName;
}

void MetaClass::setLibName(const QString& name)
{
    this->libName = name;
}

QString const & MetaClass::getLibPath() const
{
    return this->libPath;
}

void MetaClass::setLibPath(const QString& path)
{
    if (path.length() == 0)
    {
        this->libPath = this->libName;
    } else {
        this->libPath = path;
    }
}

QString const & MetaClass::getClassName() const
{
    return this->className;
}

void MetaClass::setClassName(const QString& name)
{
    this->className = name;
}

QString MetaClass::getFullName() const
{
    return this->libName + "." + this->className;
}

QMap<QString, MetaField*>& MetaClass::getFields()
{
    //QList<MetaField*> *resFields = new QList<MetaField*>(this->fields.values());

    return fields;//resFields;
}

void MetaClass::addField(MetaField* field)
{
    this->fields[field->getFieldName()] = field;
}

//QObject* MetaClass::getInstance(const QString &id)
//{
//    if (!instanceMap->contains(id)) return 0;

//    return (*instanceMap)[id];
//}

//QObject* MetaClass::instantiate(const QString& id)
//{
//    if (!instanceMap->keys().contains(id)) return 0;

//    QObject* obj = instantiate(libName, className);
//    if (obj)
//    {
//        (*instanceMap)[id] = obj;
//    }

//    return obj;
//}

QObject* MetaClass::instantiate() const
{
    return instantiate(libPath, className);
}

QObject* MetaClass::instantiate(const QString& libPath, const QString& className)
{
    qDebug() << "Creating instance of " << className << " from lib " << libPath;
    QLibrary lib(libPath);
    QObject* obj = resolveClass(&lib, className);

    return obj;
}

QObject* MetaClass::resolveClass(QLibrary* lib, const QString& className) {
    lCreate fc = (lCreate) lib->resolve("create");
    qDebug() << "Resolving create function...";
    if (fc) {
        qDebug() << "Create func resolved\n";
        return fc(className);
    } else {
        qDebug() << "Create func NOT resolved\n";
    }
    return NULL;
}


